package com.qiall.game.gobang;

import java.util.List;

public class GobangUtil {

    private static int stepLength = 5;

    /**
     * @param x
     * @param y
     */
    public static boolean check(List<RoomPool.Room.Point> points, int x, int y) {
        byte[][] board;
        int width = 12;
        int height = 15;
        board = new byte[height][];
        for (int i = 0; i < height; i++) {
            board[i] = new byte[width];
            for (int j = 0; j < width; j++) {
                board[i][j] = 0;
            }
        }
        for (RoomPool.Room.Point point : points) {
            board[point.getY()][point.getX()] = point.sessionId;
        }
        byte sessionId = board[y][x];
        // 一共四个方向都要检测
        // 1- 0
        boolean check;
        check = checkOnePosition(board, x, y, -1, 0, sessionId);
        if (check) {
            return true;
        }
        check = checkOnePosition(board, x, y, -1, 1, sessionId);
        if (check) {
            return true;
        }
        check = checkOnePosition(board, x, y, 0, 1, sessionId);
        if (check) {
            return true;
        }
        check = checkOnePosition(board, x, y, 1, 1, sessionId);
        if (check) {
            return true;
        }
        return false;
    }

    /**
     * 校验一个方向
     */
    private static boolean checkOnePosition(byte[][] board, int x, int y, int moveX, int moteY, byte sessionId) {
        int length = 1;
        int xTmp = 0;
        int yTmp = 0;
        for (int i = 1; i < stepLength; i++) {
            xTmp = x + i * moveX;
            yTmp = y + i * moteY;
            if (!xyInRange(xTmp, yTmp, board)) {
                break;
            }
            if (board[yTmp][xTmp] != sessionId) {
                break;
            }
            length++;
        }
        for (int i = 1; i < stepLength; i++) {
            xTmp = x - i * moveX;
            yTmp = y - i * moteY;
            if (!xyInRange(xTmp, yTmp, board)) {
                break;
            }
            if (board[yTmp][xTmp] != sessionId) {
                break;
            }
            length++;
        }
        return length == stepLength;
    }

    public static boolean xyInRange(int x, int y, byte[][] board) {
        if (x < 0) {
            return false;
        }
        if (x >= board[0].length) {
            return false;
        }
        if (y < 0) {
            return false;
        }
        if (y >= board.length) {
            return false;
        }
        return true;
    }
}
